package juc;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子性测试
 *
 * @author liweimin
 * @date 2021/4/22 17:16
 * @since
 */
public class AtomicDemoTest {
    public static void main(String[] args) {
        AtomicDemo atomicDemo = new AtomicDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(atomicDemo).start();
        }
    }
}

class AtomicDemo implements Runnable {
    //    private int serialNumber = 0;
    private AtomicInteger serialNumber = new AtomicInteger();

//    public int getSerialNumber() {
//        return serialNumber++;
//    }

    public int getSerialNumber() {
        return serialNumber.getAndIncrement();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " : " + getSerialNumber());
    }
}
